﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.Exceptions.Database;
using Telerik.Web.UI;
using BSCMFF.Web.UserControls.Details;
using System.Drawing;
using BSCMFF.Core;

namespace BSCMFF.Web.Pages.BSC_Setup
{
    public partial class PersonalKPIs_new : MultiLanguagePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RadGridPersonalKPIs.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
            RadGridUserPKPIsWeight.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;

            PKPI_Page_LoadMethod();
        }

        private void PKPI_Page_LoadMethod()
        {
            CheckSession();
            if (!IsPostBack)
            {
                LoadInferiorEmployees((int)Session["loggedUserID"]);
            }
            if (RadComboBoxEmployee.SelectedValue != "")
            {
                PanelEmployeePKPIs.Visible = true;
                //LoadPKPIs(Int32.Parse(RadComboBoxEmployee.SelectedValue));
            }
        }

        private void CheckSession()
        {
            if (Session["loggedUserID"] == null)
            {
                string login = HttpContext.Current.User.Identity.Name;

                BSCEntities context = new BSCEntities();

                User user = (from u in context.Users
                             where u.Login == login
                             select u).SingleOrDefault();

                if (user != null)
                {
                    Session.Add("loggedUserID", user.ID);
                }
            }
        }

        

        private void LoadInferiorEmployees(int loggedUserID)
        {
            BSCEntities context = new BSCEntities();
            List<User> users;
            //if (CheckBoxNotOkOnly.Checked == false)
            //{
                users = (from user in context.Users
                                    where user.Manager_FK == loggedUserID
                                    select user).ToList();
            //}
            //else
            //{
            //    //users = (from user in context.Users
            //    //                    where user.Manager_FK == loggedUserID// && user.TotalPKPIsWeight != 100
                                    
            //    //                    select user).ToList();

            //    //foreach (User u in users)
            //    //{
            //    //    if (u.TotalPKPIsWeight == 100)
            //    //    {
            //    //        users.Remove(u);
            //    //    }
            //    //}
            //    users = (from user in context.Users.Include("Personal_KPI")
            //             where user.Manager_FK == loggedUserID
            //             select user).ToList();

            //    var notOk = users.GroupBy(row => row.ID).Select(grouping => new
            //                        {
            //                            UserID = grouping.Key,
            //                            TotalWeight = grouping.Sum(row => row.Personal_KPI.First().Weight)
            //                        }
            //                        ).Where(g => g.TotalWeight == 100).ToList();
            //}
            RadComboBoxEmployee.DataSource = users;
            RadComboBoxEmployee.DataBind();
        }

        private void LoadPKPIs(int userID)
        {
            BSCEntities context = new BSCEntities();
            List<Personal_KPI> pkpis = (from pks in context.Personal_KPI.Include("KPI")
                                        where pks.User_FK == userID
                                        select pks).ToList();

            //RadButtonAssignEvenWeights.Visible = HiddenFieldTotalWeights.Value == "100" ? false : true;

            RadGridPersonalKPIs.DataSource = pkpis;
            RadGridPersonalKPIs.DataBind();
        }


        protected void RadGridPersonalKPIs_InsertCommand(object sender, GridCommandEventArgs e)    
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            PKPIDetails userControl = (PKPIDetails)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            //int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Personal_KPI_ID"].ToString());
            BSCEntities context = new BSCEntities();

            //Personal_KPI pkpi = (from p in context.Personal_KPI
            //                     where p.Personal_KPI_ID == id
            //                     select p).SingleOrDefault();
            Personal_KPI pkpi = new Personal_KPI();
            
            pkpi.Name = userControl.Name;
            pkpi.Description = userControl.Description;
            pkpi.Weight = userControl.Weight;
            pkpi.Measure = userControl.Measure;
            pkpi.StartValue = (int)userControl.StartValue;
            pkpi.TargetValue = (int)userControl.TargetValue;
            pkpi.CurrentValue = (int)userControl.CurrentValue;
            pkpi.User_FK = Int32.Parse(RadComboBoxEmployee.SelectedValue);
            pkpi.KPI_FK = userControl.KPI_FK;
            context.AddToPersonal_KPI(pkpi);
            try
            {
                context.SaveChanges();
            }
            catch
            {
                throw new InconsistentDatabaseException("Couldn't create personal KPI");
            }

            
        }
        protected void RadGridPersonalKPIs_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            PKPIDetails userControl = (PKPIDetails)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);



            int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Personal_KPI_ID"].ToString());
            BSCEntities context = new BSCEntities();

            Personal_KPI pkpi = (from p in context.Personal_KPI
                                 where p.Personal_KPI_ID == id
                                 select p).SingleOrDefault();

            if (pkpi != null)
            {
                pkpi.Name = userControl.Name;
                pkpi.Description = userControl.Description;
                pkpi.Weight = userControl.Weight;
                pkpi.Measure = userControl.Measure;
                pkpi.StartValue = (int)userControl.StartValue;
                pkpi.TargetValue = (int)userControl.TargetValue;
                pkpi.CurrentValue = (int)userControl.CurrentValue;
                pkpi.KPI_FK = userControl.KPI_FK;
                //pkpi.User_FK = Convert.ToInt32((userControl.FindControl("ComboBoxUsers") as RadComboBox).SelectedValue);

                try
                {
                    context.SaveChanges();
                }
                catch
                {
                    throw new InconsistentDatabaseException("Couldn't save personal KPI");
                }

            }

        }

        protected void RadGridPersonalKPIs_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            PKPIDetails userControl = (PKPIDetails)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);



            int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Personal_KPI_ID"].ToString());
            BSCEntities context = new BSCEntities();

            Personal_KPI pkpi = (from p in context.Personal_KPI
                                 where p.Personal_KPI_ID == id
                                 select p).SingleOrDefault();

            if (pkpi != null)
            {

                context.DeleteObject(pkpi);

                try
                {
                    context.SaveChanges();
                }
                catch
                {
                    throw new InconsistentDatabaseException("Couldn't delete personal KPI");
                }
            }
        }

        int totalWeight = 0;
        protected void RadGridPersonalKPIs_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataItem = e.Item as GridDataItem;
                int fieldValue = int.Parse(dataItem["Weight"].Text);
                totalWeight += fieldValue;
            }
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footerItem = e.Item as GridFooterItem;
                footerItem["Weight"].Text = "Total " + totalWeight.ToString();
                HiddenFieldTotalWeights.Value = totalWeight.ToString();
                if (totalWeight == 100)
                {
                    footerItem["Weight"].ForeColor = Color.Green;
                }
                else
                {
                    footerItem["Weight"].ForeColor = Color.Red;
                }
            }
        }

        protected void RadGridPersonalKPIs_DataBound(object sender, EventArgs e)
        {
            if (HiddenFieldTotalWeights.Value != "0")
            {
                RadButtonAssignEvenWeights.Visible = true;
            }
            else
            {
                RadButtonAssignEvenWeights.Visible = false;
            }
        }

        protected void RadButtonAssignEvenWeights_Click(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();

            int userID = Int32.Parse(RadComboBoxEmployee.SelectedValue);

            List<Personal_KPI> pkpis = (from pkpi in context.Personal_KPI
                                        where pkpi.User_FK == userID
                                        select pkpi).ToList();
            if (pkpis.Count == 1)
            {
                pkpis[0].Weight = 100;
            }
            if (pkpis.Count == 0)
            {
                return;
            }
            int averageUp = (int)Math.Ceiling((decimal)(100 / (decimal)pkpis.Count));
            int averageDown = (int)Math.Floor((decimal)(100 / (decimal)pkpis.Count));

            int totalSoFar = 0;
            for (int i = 0; i < pkpis.Count - 1; ++i)
            {
                int average = i % 2 == 0 ? averageUp : averageDown;
                pkpis[i].Weight = average;
                totalSoFar += average;
            }
            if (pkpis.Count >= 2)
            {
                pkpis[pkpis.Count - 1].Weight = 100 - totalSoFar;
            }

            try
            {
                context.SaveChanges();
                RadGridPersonalKPIs.Rebind();
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't even weights: " + ex.Message);
            }
        }

        protected void CheckBoxNotOkOnly_Changed(object sender, EventArgs e)
        {
            LoadInferiorEmployees((int)Session["loggedUserID"]);
        }

        protected void RadGridUserPKPIsWeight_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            BSCEntities context = new BSCEntities();
            int loggedUserID = (int)Session["loggedUserID"];

            var users = (from user in context.Users
                         where user.Manager_FK == loggedUserID
                         select user).ToList();

            RadGridUserPKPIsWeight.DataSource = users;
        }
    }
}